package com.liyunc.demo.custom.livechat.client;

import com.liyunc.demo.custom.livechat.manager.MainWindowFactory;

import java.io.*;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

class ReadMes extends Thread {

    private final Socket socket;

    public ReadMes(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String message = null;
            ChatWindow chatWindow = MainWindowFactory.getChatWindow();
            while (true) {
                if (socket.isConnected()) {
                    if (!socket.isInputShutdown()) {
                        message = reader.readLine();
                        if (message != null) {
                            message += "\n";
                            chatWindow.contentArea.append(message);
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class SendMes extends Thread {

    private final Socket socket;
    private final String message;

    public SendMes(Socket socket, String message) {
        this.socket = socket;
        this.message = message;
    }

    @Override
    public void run() {
        PrintWriter out = null;
        try {
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                    socket.getOutputStream())), true);
            if (socket.isConnected()) {
                if (!socket.isOutputShutdown()) {
                    out.println(message);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public class Client {

    Socket socket;

    public Client() throws IOException {
        this.socket = new Socket("127.0.0.1", 4000);
    }
}